<template>
  <div style="text-align: left">
    <el-button
      class="add-button"
      type="success"
      @click="dialogFormVisible = true"
    >添加角色</el-button>
    <el-dialog
      title="添加角色"
      :visible.sync="dialogFormVisible"
      width="25%"
      @close="clear"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-position="left"
        label-width="0px"
      >
        <el-form-item prop="name">
          <el-input
            v-model="roleForm.name"
            type="text"
            auto-complete="off"
            placeholder="角色权限"
          />
        </el-form-item>
        <el-form-item prop="nameZh">
          <el-input
            v-model="roleForm.nameZh"
            type="text"
            auto-complete="off"
            placeholder="角色描述"
          />
        </el-form-item>

        <el-form-item prop="description">
          <el-input
            v-model="roleForm.description"
            type="text"
            auto-complete="off"
            placeholder="自我描述"
          />
        </el-form-item>

        <el-form-item style="width: 100%">
          <el-button
            type="primary"
            style="width: 100%; background: #505458; border: none"
            @click="createRole"
          >添加</el-button>
        </el-form-item>
        <el-form-item label="菜单栏配置" label-width="120px" prop="menus">
          <el-tree
            ref="tree"
            :data="menus"
            :props="props"
            show-checkbox
            node-key="id"
            accordion
            @check="handleCheckChange"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import Cookies from 'js-cookie'

export default {
  name: 'RoleCreate',
  data() {
    return {
      dialogFormVisible: false,
      timer: null,
      menus: [],
      title: [],
      treeArr: [],
      props: {
        id: 'id',
        label: 'title',
        children: 'children'
      },
      rules: {
        name: [{ required: true, message: '角色名不能为空', trigger: 'blur' }]
      },
      checked: true,
      roleForm: {
        name: '',
        nameZh: '',
        description: ''
      }
    }
  },

  mounted() {
    this.listMenus()
  },
  methods: {
    clear() {
      this.roleForm = {
        name: '',
        nameZh: '',
        description: ''
      }
      this.$nextTick(() => {
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([])
        }
      })
    },

    listMenus() {
      var _this = this
      this.$axios.get('/api/admin/role/menu').then((resp) => {
        if (resp.status === 200) {
          _this.menus = resp.data.data
        }
      })
    },
    // 获取选中节点
    handleCheckChange() {
      var a = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys())
      this.treeArr = JSON.parse(JSON.stringify(a))
      console.log(this.treeArr)
    },

    createRole() {
      this.$axios
        .post('/api/admin/role', {
          role: this.roleForm,
          id: this.treeArr
        })
        .then((resp) => {
          console.log(resp)
          if (resp.status === 200) {
            this.$alert(resp.data.data, '提示', {
              confirmButtonText: '确定'
            })
            this.clear()
            this.$emit('onSubmit')
          }
        })
        .catch((error) => {
          // console.log(error.response);
          Message.error(error.response.data.message + '3s后即将重新登录')
          removeToken()

          clearTimeout(this.timer) // 清除延迟执行
          this.timer = setTimeout(() => {
            // 设置延迟执行
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
            window.localStorage.clear()
            this.$router.push('/login')
          }, 3000)
        })
      this.dialogFormVisible = false
    },

    // 单条删除
    handleDelete(index, row) {
      console.log(row.id)
      const _id = row.id
      this.$axios
        .delete('/api/admin/user/del', { data: { id: _id }})
        .then((resp) => {
          // console.log(resp);
          if (resp.status === 200) {
            this.$message.success(resp.data.data)
            this.reload()
          }
        })
        .catch((error) => {
          Message.error(error.response.data.message)
          this.reload()
        })
    },
    // 批量删除
    delchoose() {
      console.log('---------------------------')
      // 监听选中框的个数，定义变量承载选中的个数
      const length = this.multipleSelection.length
      console.log(length)
      if (length < 2) {
        this.$message.error('请至少选择两条数据')
      } else {
        for (let i = 0; i < length; i++) {
          // console.log(this.multipleSelection[i])
          this.delarr.push(this.multipleSelection[i].id)
          console.log(this.delarr[i])
        }
        // let resdata = JSON.parse(JSON.stringify(this.delarr));
        const resdata = JSON.stringify(this.delarr)
        console.log(resdata)
        this.$axios
          .delete('/api/admin/user/delMore', {
            params: {
              users: this.delarr
            },
            paramsSerializer: (params) => {
              return this.$qs.stringify(params, { indices: false })
            }
          })
          .then((resp) => {
            // console.log(resp);
            if (resp.status === 200) {
              this.$message.success(resp.data.data)
              this.reload()
              console.log(resp)
            }
          })
          .catch((error) => {
            Message.error(error.response.data.message)
            this.reload()
          })
      }
    }
  }
}
</script>

<style scoped>
.add-button {
  margin: 18px 0 0 10px;
}
</style>
